"use strict";
/**
 * Visualization map spatial data service R&$D
 * @author Oran
 * @version 1.1
 * @time 2021/3/26
 */
(function (window) {
  class gear {
    constructor(viewer) {
      this.viewer = viewer;
      this.DynamicDraw = undefined;

      this.Rain = null; //雨
      this.Snow = null; //雪
      this.Fog = null; //雾
    }

    //#region example
    //抛出全部方法
    findProperties(obj, ...arg) {
      function getProperty(new_obj) {
        if (new_obj.__proto__ === null) {
          //说明该对象已经是最顶层的对象
          return [];
        }

        let properties = Object.getOwnPropertyNames(new_obj);

        let arr = [];

        arg.forEach(v => {
          const newValue = properties.filter(property => {
            return property.startsWith(v);
          });

          if (newValue.length > 0) {
            arr = arr.concat(newValue);
          }
        });

        return [...arr, ...getProperty(new_obj.__proto__)];
      }

      return getProperty(obj);
    }

    //释放方法
    release() {
      this.findProperties($G, "").forEach(model => {
        if (model.indexOf("Release") != -1) {
          var e = eval("$G." + model);
          e(this.viewer);
        }
      });
    }

    uuid() {
      var temp_url = URL.createObjectURL(new Blob());
      var uuid = temp_url.toString(); // blob:https://xxx.com/b250d159-e1b6-4a87-9002-885d90033be3
      URL.revokeObjectURL(temp_url);
      return uuid.substr(uuid.lastIndexOf("/") + 1);
    }
    //#endregion

    //#region 其他实列
    /**
     * 加载底图
     */
    addBaseLayer() {
      // $G.BaseLayer(this.viewer, {
      //   //离线数据
      //   name: "影像底图",
      //   type: "arcgis_cache",
      //   url: "http://192.168.0.69/mapdata/33010901001/tiles/arcgis_img/L{arc_z}/R{arc_y}/C{arc_x}.jpg",
      //   brightness: 2,
      // });

      // $G.BaseLayer(this.viewer, {
      //   //高德
      //   name: "影像底图",
      //   type: "www_gaode",
      //   layer: "img_d",
      // });

      // //天地图
      // $G.BaseLayer(this.viewer, {
      //   name: "影像底图",
      //   type: "tdt",
      //   layer: "img_w",
      // });
      // //天地图道路数据
      // $G.BaseLayer(this.viewer, {
      //   name: "影像底图",
      //   type: "tdt",
      //   layer: "cia_w",
      // });

      $G.BaseLayer(this.viewer, {
        name: "影像底图",
        type: "mapbox",
        layer: "blue",
      });
    }
    /**
     * 加载底图
     */
     addBaseLayer_GaoDe() {

      $G.BaseLayer(this.viewer, {
        //高德
        name: "影像底图",
        type: "www_gaode",
        layer: "img_d",
      });
    }
    /**
     * 日照
     */
    example_runshineAnalysis() {
      var setvisible = $G.E.runshineAnalysis();
      setvisible(this.viewer, "play"); //stop
    }

    //电子标签
    electronicLabel(params){


      let value = {
        diagnosis: "14818339123914752021435054816809234433",
        equipmentName: "#001",
        grade: 3,
        header: "电子标签",
        index: "1422376119138533378",
        popupIndex: 1,
        recordId: "",
        text: "",
        text1: "#0001",
        text2: "",
        text3: "",
        txt: "#1出现紧急事件！"
      };

      let btn_id = "123456";
      var click = "window.parent.postMessage({name : 'example_pump_popup',type:'electron_lable_cancel',value : '" + params.id + "'} , '*');";
      var click_cancleBtn = "window.parent.postMessage({name : 'example_pump_popup',type:'electron_lable_cancel',value : '" + params.id + "'} , '*');";
      var html = [
        '<div id="' +
        "this.trackPopUpContentId" +
        '" class="cesium-popup" style="top:0;left:0;">' +
        '<div class="cesium-prompt-content-wrapper" id="' +
        "this.promptDivId" +
        '">' +
        '<div id="trackPopUpLink" class="cesium-popup-content" style="">' +
        '<span class="promptContent" id="' +
        "this.promptContentId" +
        '">' +
        "this.content" +
        "</span>" +
        "</div>" +
        "</div>" +
        "</div>",
        '<div id="' +
        "this.trackPopUpContentId" +
        '" class="cesium-popup" style="top:0;left:0;">' +
        '<a class="cesium-popup-close-button" href="javascript:void(0)" id="' +
        "this.closeBtnId" +
        '">×</a>' +
        '<div class="cesium-popup-content-wrapper" id="' +
        "this.promptDivId" +
        '">' +
        '<div id="trackPopUpLink" class="cesium-popup-content" style="">' +
        '<span class="popupContent" id="' +
        "this.promptContentId" +
        '">' +
        "this.content" +
        "</span>" +
        "</div>" +
        "</div>" +
        '<div class="cesium-popup-tip-container">' +
        '<div class="cesium-popup-tip"></div>' +
        "</div>" +
        "</div>",
      ];

      var content1 =
        `<div style="">
                      <div style=;" onclick="` +
        click +
        `">` +
        value.txt +
        `<div/>
                      </div>`;

      var content2 =
        `<div style="">
                          <div style=" " onclick="` +
        click +
        `">` +
        value.header +
        `
                          <div style="">` +
        value.text1 +
        `</div>
                          <div style="">` +
        value.text2 +
        `</div>
                          <div style="">` +
        value.text3 +
        `</div><div/>
                          <div class="popupButton" style="" onclick="window.parent.postMessage({name : 'example_pump_popup',type:'click',type : '1',ButtonId : '` +
        btn_id +
        `',diagnosis : '` +
        value.diagnosis +
        `',deal_type:'` +
        value.deal_type +
        `',value:'` +
        value +
        `'} , '*');">查看1</div>
                          <div class="popupButton" style="" onclick="window.parent.postMessage({name : 'example_pump_popup',type:'2',ButtonId : '` +
        btn_id +
        `',diagnosis : '` +
        value.diagnosis +
        `',deal_type:'` +
        value.deal_type +
        `',recordId:'` +
        value.recordId +
        `',equipmentName:'` +
        value.equipmentName +
        `',value:'` +
        params.id +
        `'} , '*');">处理</div>
                      </div>`;

      var content3 =
        `
          <div class="box9" style="box-shadow: 0px 0px 10px #d93f3f;
          border-radius:5px;
          color: #fff;
          position: absolute;
          top: 94px;
          left: 38px;
          height: 34px;
          background-color: #ff4242b3;
          width: 166px;
          backdrop-filter: blur(10px);
              ">
                <div title="${value.header}:${value.equipmentName}"  class="section4 flex-row justify-between" style="width: 91px !important;overflow: hidden !important;white-space: nowrap !important;
                text-overflow: ellipsis !important;padding: 8px 0 0 10px;font-size: 12px; font-weight: 700;
                height: 21px;">
                  <span style=" " class="word30" >${value.header}:${value.equipmentName}</span>
                  <div class="popupButton" style="width: 49px;z-index:999;color: #fff;cursor: pointer;position: absolute;top: 5px;left: 105px;" onclick="window.parent.postMessage({name : 'example_pump_popup',type:'electron_lable_detail',ButtonId : '` +
        btn_id +
        `',diagnosis : '` +
        value.diagnosis +
        `',deal_type:'` +
        value.deal_type +
        `',recordId:'` +
        value.recordId +
        `',equipmentName:'` +
        value.equipmentName +
        `',value:'` +
        params.id +
        `'} , '*');">查看</div>
                </div>
              </div>
          `;

      var content = content1;
      switch (value.popupIndex) {
        case 0:
          content = content2;
          break;
        case 1:
          content = content3;
          break;
      }
      // element.destroy(); //销毁
      if (value.popupIndex == null) {
        value.popupIndex = 1;
      }


      var popup = new window.control.MovePrompt(this.viewer, {
          id:$G.uuid(),
          type: 2,
          popupCartesian: Cesium.Cartesian3.fromDegrees(params.position.x, params.position.y,params.position.z),
          content: content == null ?
          `
              <div>
                  <span>提示框<br/>
              </div>
          `:content,
          innerHTML:html
      });


      popup.id = btn_id;
      popup.grade = value.grade;
      // _this.MovePromptList[i] = popup;

      // var _uri = "/assets/";
      var _uri = "/3D/assets/";

      if (value.grade == 3) {
        
        $(".cesium-popup-tip").css("width", "42px");
        $(".cesium-popup-tip").css("height", "66px");
        $(".cesium-popup-tip").css("background", "url(/static/3d/assets/images/SketchPng.png) 0px 1px no-repeat");
        $(".cesium-popup-tip").css("box-shadow", "0 3px 14px rgb(0 0 0 / 0%)");
        $(".cesium-popup-tip").css("transform", "none");
        $(".cesium-popup-tip").css("margin", "0px auto 0");
        $(".cesium-popup-tip-container").css("height", "66px");
      }

      switch (value.popupIndex) {
        case 0:
          // $(".cesium-popup-tip").css("background","#ff4b61");
          break;
        default:
          // $(".cesium-popup-tip").css("background","#0a1f31ba");
          break;
      }

    }

    //POI标注
    poiLabel(params){  
      var viewer = this.viewer;
      $G.add_POI_Lable(viewer,params);
    }

    //销毁POI标注
    destroy_PoiLable(data){
      var viewer = this.viewer;
      $G.destroy_aMODEL(viewer,{id:data.id});
    }

    //电子围栏
    electronicFence(params){

      var pointList = [
            106.24923009714767,38.47125135879477, 50,
            106.25177281885625,38.470870997179034, 50,
            106.25177281885625,38.47087099717903, 50,
            106.25653064969968,38.469880541275394, 50,
            106.26019173160856,38.46885943576771, 50,
            106.26257452888983,38.46834537419175, 50,
            106.26786331623687,38.46706579987463, 50,
            106.27184915548607,38.4660325153687, 50,
            106.28193126353587,38.46351738752997, 50,
            106.28013477846444,38.45761635162833, 50,
            106.27967079229916,38.457496117879906, 50,
            106.27936376310038,38.457107654882904, 50,
            106.26973056066342,38.45978816395609, 50,
            106.26870818617078,38.45671628638913, 50,
            106.26465715917034,38.45777279966089, 50,
            106.26193599479984,38.4584815700937, 50,
            106.259845588311,38.45894233771531, 50,
            106.25624234698094,38.45861963461821, 50,
            106.25451335925966,38.45846474455399, 50,
            106.2535935675155,38.462150670755236, 50,
            106.2539405349399,38.462950355131404, 50,
            106.25209622118788,38.46288928538285, 50,
            106.24999726241508,38.46774470153269, 50,
            106.2488169660283,38.46953777475364, 50,
            106.24872581666553,38.471268659080216, 50,
            106.24923009714767,38.47125135879477, 50,
        ]
      let imgUrl = "http://121.40.42.254:8008/arrow.png";
      $G.E.electronicFence(this.viewer,pointList,imgUrl);
    }

    //告警
    alarm(params){
      $G.E.Spread(this.viewer,{
        x: params.position.x,
        y: params.position.y,
        z: params.position.z,
        size: 500.1,
      });
    }

    //波纹
    circleRipple(params){
      $G.circleRipple(this.viewer,{
        x: params.position.x,
        y: params.position.y
      });
    }

    //雷达扫描
    raderScan(params){
      $G.raderScan(this.viewer,{
        x: 106.26847440010566,
        y: 38.46078634170007
      });
    }

    //道路线
    roadLine(){
      let that = this;
      let url = "./assets/geojson/roadLine.geojson";
      Cesium.GeoJsonDataSource.load(url).then(function(dataSource) {
        
          that.viewer.dataSources.add(dataSource);
          const entities = dataSource.entities.values;
          for (let i = 0; i < entities.length; i++) {
              let entity = entities[i];
              entity.polyline.width = 1.7;
              entity.polyline.material = new Cesium.DiySpriteline1MaterialProperty(1000, '/static/3d/assets/images/spriteline1.png');
          }
      });
    }

    //上升粒子
    ascendingParticle(){

      $G.ascendingParticle(this.viewer,[106.2323817,38.4249494,106.31741603,38.51653385]);

    }
    //旋转点位
    rotationPoint(params){

      let url = "";
      if(window.Intranet){
          //业主服务器
          url = "http://172.31.113.201:6080/数据/pyramid.glb";
      }else{
          //阿里云服务器
          url = "http://121.40.42.254:8083/模型数据/pyramid.glb";
      }

      let points =
        {
          id: 8,
          lon: params.position.x,
          lat: params.position.y,
          height: params.position.z,
          heading: 0,
          pitch: 0,
          roll: 0,
          uri: url,
          scale: 100,
          rotateSpeed: 6, // 转速
          minimumPixelSize: 20, // 模型最小以多少像素显示
          duration: 19
        };


      let modelColor = new Cesium.Color.fromCssColorString('rgba(0,255,255,0.5)'); // 模型颜色
      let position = Cesium.Cartesian3.fromDegrees(points.lon,points.lat,points.height);
      let hpr = new Cesium.HeadingPitchRoll(
                  Cesium.Math.toRadians(points.heading),  
                  Cesium.Math.toRadians(points.pitch), 
                  Cesium.Math.toRadians(points.roll)   
                );
      let modelMatrix = Cesium.Transforms.headingPitchRollToFixedFrame(position,hpr);
      let model_glb = this.viewer.scene.primitives.add(
                    Cesium.Model.fromGltf({
                      id: points.id,
                      url: points.uri,
                      scale: points.scale,
                      modelMatrix: modelMatrix,
                      color: modelColor,
                      colorBlendMode: Cesium.ColorBlendMode.MIX,
                      maximumScale: 5000,
                      minimumPixelSize:  points.minimumPixelSize,
                      scene: this.viewer.scene,
                      heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND
                    })
                  );
      let modeA = Cesium.ColorBlendMode.HIGHLIGHT;   //Cesium.ColorBlendMode.HIGHLIGHT   Cesium.ColorBlendMode.MIX   Cesium.ColorBlendMode.REPLACE
      model_glb.colorBlendMode = modeA;
      model_glb.attributes = points;
      model_glb.heading = points.heading
      let that = this;
      model_glb.readyPromise.then(function(model_param) {

        const setIntervalId = setInterval(() => {

          model_param.heading += Cesium.Math.toRadians(model_glb.attributes.rotateSpeed);
          model_param.modelMatrix = that.diyChangeModelMatrix(model_param);
        }, model_glb.attributes.duration);
        model_param.setIntervalId = setIntervalId; // 用于清除定时器
      });
    }

    diyChangeModelMatrix(model) {
      // model.heading += Cesium.Math.toRadians(model.attributes.rotateSpeed || 0)
      const pitch = Cesium.defaultValue(model.attributes.pitch, 0.0);
      const roll = Cesium.defaultValue(model.attributes.roll, 0.0);
      const hpr = new Cesium.HeadingPitchRoll(model.heading, pitch, roll);
  
      const position = Cesium.Cartesian3.fromDegrees(
        model.attributes.lon,
        model.attributes.lat,
        model.attributes.height
      );
      const modelMatrix = Cesium.Transforms.headingPitchRollToFixedFrame(position,hpr);
      return modelMatrix;
    }

    /**
     * 画点
     */
    example_drawPoint() {
      //刷新指引
      this.setTitle({
        text: "单击鼠标，右键结束画点",
        title: "提示",
      });

      $G.drawPoint(this.viewer, function (id) {
        console.log(id);
      });
    }

    /**
     * 初始化绘制类
     */
    initDynamicDraw() {
      this.DynamicDraw = new $G.D.DynamicDrawer(this.viewer, {
        id: $G.uuid(),
        _style: {
          labelTransparency: 100, //字体透明度
          outlineColor: "#3462d0", //字体边框颜色
          fillColor: "#fff", //字体颜色
          PolylineColor: "#fff",
          PolylineWitch: 3, //线条宽度
          shapeColor: "#fff",
          shapeTransparency: 50, //形状透明度
          borderWitch: 2, //边框宽度
          borderColor: "#3462d0",
          borderTransparency: 80, //边框透明度
        },
      });
    }

    /**
     * 线面⚪
     * @param {*} type 'drawPolyline': //画折线 'drawPolygon': //画多边形 'drawRectangle': //画矩形 'drawCircle': //画圆
     */
    example_DynamicDraw(type) {
      this.initDynamicDraw();
      function _(positions) {
        var p = [];
        positions.forEach(element => {
          var cartographic = Cesium.Cartographic.fromCartesian(element);
          var lng = Cesium.Math.toDegrees(cartographic.longitude);
          var lat = Cesium.Math.toDegrees(cartographic.latitude);
          var height = cartographic.height; //模型高度
          var mapPosition = { x: lng, y: lat, z: height };

          p.push(mapPosition);
        });
        return p;
      }
      //刷新指引
      this.setTitle({
        text: "单击起始点，移动鼠标至节点，再次单机，右键结束画点",
        title: type,
      });

      switch (type) {
        case "drawPolyline": //画折线
          this.DynamicDraw.drawPolyline(function (positions) {
            console.log(_(positions));
          });
          break;
        case "drawPolygon": //画多边形
          this.DynamicDraw.drawPolygon(function (positions) {
            console.log(_(positions));
          });
          break;
        case "drawRectangle": //画矩形
          this.DynamicDraw.drawRectangle(function (positions) {
            console.log(_(positions));
          });
          break;
        case "drawCircle": //画圆
          this.DynamicDraw.drawCircle(function (positions) {
            console.log(_(positions));
          });
          break;

        default:
          break;
      }
    }

    /**
     * 初始化测算类
     */
    initMeasureDraw() {
      this.DynamicDraw = new $G.D.DynamicDrawer(this.viewer, {
        id: $G.uuid(),
        type: "测量", //默认为空就是绘制
        _style: {
          backgroundColor: "#000",
          labelTransparency: 80, //字体透明度
          outlineColor: "#fff", //字体边框颜色3462d0
          fillColor: "#fff", //字体颜色
          PolylineColor: "#fff",
          PolylineWitch: 3, //线条宽度
          shapeColor: "#fff",
          shapeTransparency: 50, //形状透明度
          borderWitch: 2, //边框宽度
          borderColor: "#3462d0",
          borderTransparency: 80, //边框透明度
        },
      });
    }

    /**
     * 测长度 面积
     * @param {*} type 'drawPolyline': //测折线 'drawPolygon': //测多边形
     */
    example_measureDraw(type) {
      this.initMeasureDraw();
      switch (type) {
        case "measurePolyline": //测折线
          this.DynamicDraw.drawPolyline(function (positions) {
            console.log(positions);
          });
          break;
        case "measurePolygon": //测多边形
          this.DynamicDraw.drawPolygon(function (positions) {
            console.log(positions);
          });
          break;
        default:
          break;
      }
    }

    //测高
    example_measureLineFlat() {
      $G.M.measureHeight(this.viewer);
    }
    //删除测高
    example_deleteAltimetry() {
      $G.M.deleteAltimetry(this.viewer);
    }
    //释放编辑
    example_measure_release() {
      this.example_deleteAltimetry();
    }

    //编辑图形
    example_editEntity() {
      if (this.DynamicDraw) this.DynamicDraw.setMode(1);
    }
    //删除图形
    example_deleteEntity() {
      if (this.DynamicDraw) this.DynamicDraw.setMode(2);
    }

    //释放编辑
    example_edit_release() {
      $G.entities.Release(this.viewer);
    }

    /**
     * 添加导航控件
     */
    example_addNavigation() {
      $G.C.NavigationBox(this.viewer, {
        x: 0,
        y: 0,
        z: 10000,
        heading: 0,
        pitch: 0,
        roll: 0,
      });
    }
    /**
     * 添加鼠标控件
     */
    example_addPositionBox() {
      $G.C.MousePositionBox(this.viewer, "mapBox");
    }

    /**
     * 着色器下雪
     */
    example_snowSystem_Shaders() {
      this.Snow =
        this.Snow == null
          ? new $G.E.Effect(this.viewer, {
            visibility: 0.2,
            show: false,
            type: "x",
            color: new Cesium.Color.fromCssColorString("#e7e7e7"), //new Cesium.Color(0.8, 0.8, 0.8, 0.3)
          })
          : this.Snow; //雪
      if (!this.Snow._show) this.Snow.show(true);
      else this.Snow.show(false);
      return this.Snow;
    }
    /**
     * 着色器下雨
     */
    example_RainwaterSystem_Shaders() {
      this.Rain =
        this.Rain == null
          ? new $G.E.Effect(this.viewer, {
            visibility: 0.2,
            show: false,
            type: "y",
            color: new Cesium.Color.fromCssColorString("#e7e7e7"), //new Cesium.Color(0.8, 0.8, 0.8, 0.3)
          })
          : this.Rain; //雨
      if (!this.Rain._show) this.Rain.show(true);
      else this.Rain.show(false);
      return this.Rain;
    }
    /**
     * 着色器雾
     */
    example_Fogging() {
      this.Fog =
        this.Fog == null
          ? new $G.E.Effect(this.viewer, {
            visibility: 0.2,
            show: false,
            type: "w",
            color: new Cesium.Color.fromCssColorString("#e7e7e7"), //new Cesium.Color(0.8, 0.8, 0.8, 0.3)
          })
          : this.Fog; //雾
      if (!this.Fog._show) this.Fog.show(true);
      else this.Fog.show(false);
      return this.Fog;
    }

    //更新指引内容
    setText(params, title) {
      if (title) this.setTitle(title);
      let doc = document.getElementsByClassName("notes")[0];
      if (doc == null) return;
      if (!title) doc.innerHTML = "操作指引<br>";

      for (let index = 0; index < params.length; index++) {
        const element = params[index];
        let dom = document.createElement("p");
        dom.setAttribute("style", " font-weight: 700; ");
        dom.innerHTML = element.name;
        doc.appendChild(dom);
        doc.innerHTML += element.text + "<br>";
      }
    }

    //更新指引标题
    setTitle(params) {
      let travelscope = document.getElementById("travelscope");
      if (travelscope == null) return;
      travelscope.innerHTML = params.title;
      let dom = document.createElement("div");
      dom.setAttribute("class", "notes");
      dom.innerHTML = params.text + "<br>";
      travelscope.appendChild(dom);
    }

    //#endregion

    //#region 银川逻辑代码

    flyTo(param){
      // $G.flyTo(viewer,{x:106.188131,y:38.411423,z:5073.91,h:1.12,p:-0.36686,r:0,duration:2});
      $G.flyTo(this.viewer,param);
    }

    getPerspective(param){
      $G.getPerspective(this.viewer,param);
    }

    /**
     * 加载两个倾斜摄影模型
     */
    addTiltPhotography(id,name) {
      if(name == "银川"){
        let url = "";
        if(window.Intranet){
            //业主服务器
            url = "http://172.31.113.201:6080/数据/银华社区-output/tileset.json";
        }else{
            //阿里云服务器
            url = "http://121.40.42.254:8008/%E9%93%B6%E5%B7%9D-%E5%80%BE%E6%96%9C%E6%91%84%E5%BD%B1/%E9%93%B6%E5%8D%8E%E7%A4%BE%E5%8C%BA-output/tileset.json";
        }
        $G.aTiles(
          this.viewer,
          {
            type: "tiltPhotography",
            name: "银川社区",
            id: id,
            url: url,
            flyTo: true,
            heightOffset: 1068,
            height: 0,
          },
          {
            color: "color('white', 1)",
            show: true,
          }
        );
      }else if(name == "新华商圈"){
        let url = "";
        if(window.Intranet){
            //业主服务器
            url = "http://172.31.113.201:6080/数据/新华商圈-output/tileset.json";
        }else{
            //阿里云服务器
            url = "http://121.40.42.254:8008/%E9%93%B6%E5%B7%9D-%E5%80%BE%E6%96%9C%E6%91%84%E5%BD%B1/%E6%96%B0%E5%8D%8E%E5%95%86%E5%9C%88-output/tileset.json";
        }
        $G.aTiles(
          this.viewer,
          {
            type: "tiltPhotography",
            name: "新华商圈",
            id: id,
            url: url,
            flyTo: true,
            heightOffset: 1068,
            height: 0,
          },
          {
            color: "color('white', 1)",
            show: true,
          }
        );
      }else if(name == "宁夏"){
        let url = "";
        if(window.Intranet){
            //业主服务器
            url = "http://172.31.113.201:6080/数据/宁夏修改后osgb-output/tileset.json";
        }else{
            //阿里云服务器
            url = "http://121.40.42.254:8008/%E9%93%B6%E5%B7%9D-%E5%80%BE%E6%96%9C%E6%91%84%E5%BD%B1/%E5%AE%81%E5%A4%8F%E4%BF%AE%E6%94%B9%E5%90%8Eosgb-output//tileset.json";
        }
        $G.aTiles(
          this.viewer,
          {
            type: "tiltPhotography",
            name: "宁夏",
            id: id,
            url: url,
            flyTo: true,
            heightOffset: 1065,
            height: 0,
          },
          {
            color: "color('white', 1)",
            show: true,
          }
        );
      }

      return {
        code: 0,
        method: "event_init_ok",
        data: {},
        msg: "success",
      };
    }
    DiyCameraMoveEndListener(){//监听摄像机视角高度
      let that = this;
      var handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
      //滚轮滚动
      handler.setInputAction(function (evnet) {
        let viewingAnglePosition = $G.C.getCameraView(that.viewer);
        window.parent.postMessage({type:'camera_listener_z',value:viewingAnglePosition.z}, '*');
      }, Cesium.ScreenSpaceEventType.WHEEL);
    }
    addWmtsMap(viewer,params) {
      // var url = 'http://172.31.119.254:8090/iserver/services/map-ugcv5-YXdataL180124/rest/maps/YXdataL180124';
      var url = params.url;
      var options = options || {};
      var scales84 = [3.38032714321E-9, 6.76065428641E-9, 1.352130857282E-8, 2.704261714564E-8, 5.408523429128E-8, 1.0817046858257E-7, 2.1634093716514E-7, 4.3268187433028E-7, 8.6536374866056E-7, 1.73072749732112E-6, 3.46145499464224E-6, 6.92290998928448E-6, 1.3845819978568952E-5, 2.7691639957137904E-5, 5.538327991427581E-5, 1.1076655982855162E-4, 2.2153311965710323E-4, 4.4306623931420646E-4, 8.861324786284129E-4, 0.0017722649572568258, 0.0035445299145136517, 0.007089059829027303];

      var scalesweb = [1.69016357160E-9, 3.38032714321E-9, 6.76065428641E-9, 1.352130857282E-8, 2.704261714564E-8, 5.408523429128E-8, 1.0817046858257E-7, 2.1634093716514E-7, 4.3268187433028E-7, 8.6536374866056E-7, 1.73072749732112E-6, 3.46145499464224E-6, 6.92290998928448E-6, 1.3845819978568952E-5, 2.7691639957137904E-5, 5.538327991427581E-5, 1.1076655982855162E-4, 2.2153311965710323E-4, 4.4306623931420646E-4, 8.861324786284129E-4, 0.0017722649572568258, 0.0035445299145136517, 0.007089059829027303];

      $.ajax({
        type: "get",
        url: url + '.json',
        success: function (result) {
          console.log(result)
          var name = result.name;
          //var rectangle = Cesium.Rectangle.fromDegrees(result.bounds.left, result.bounds.bottom, result.bounds.right, result.bounds.top)
          var rectangle = Cesium.Rectangle.fromDegrees(-180, -90, 180, 90)
          var epsgcode = result.prjCoordSys.epsgCode
          var tilingScheme = ''
          var minlevel = 0
          var maxlevel = 22

          var originx = 0
          var originy = 0

          if (epsgcode === 4326) {
            tilingScheme = new Cesium.GeographicTilingScheme({
              numberOfLevelZeroTilesX: 2,
              numberOfLevelZeroTilesY: 1
            })
            originx = -180
            originy = 90
            if (options.minimumLevel !== undefined) {
              minlevel = options.minimumLevel
            } else {
              minlevel = 1
            }
            if (options.maximumLevel !== undefined) {
              maxlevel = options.maximumLevel
            } else {
              maxlevel = 19
            }
          }
          if (epsgcode === 3857) {
            tilingScheme = new Cesium.WebMercatorTilingScheme()
            originx = -20037508.34
            originy = 20037508.34
            if (options.minimumLevel !== undefined) {
              minlevel = options.minimumLevel
            } else {
              minlevel = 1
            }
            if (options.maximumLevel !== undefined) {
              maxlevel = options.maximumLevel
            } else {
              maxlevel = 19
            }
          }

          var layerProvider = new Cesium.UrlTemplateImageryProvider({
            url: url + "/tileImage.png?transparent=true&cacheEnabled=true&width=256&height=256&x={x}&y={y}&scale={scale}&redirect=false&overlapDisplayed=false&origin={'x':" + originx + ",'y':" + originy + "}",
            rectangle: rectangle,
            minimumLevel: minlevel || 0,
            maximumLevel: maxlevel || 22,
            tilingScheme: tilingScheme,
            customTags: {
              scale: function (imageryProvider, x, y, level) {
                if (epsgcode === 4326) {
                  return scales84[level]
                }
                if (epsgcode === 3857) {
                  return scalesweb[level]
                }

              }
            }

          });

          var layer = viewer.imageryLayers.addImageryProvider(layerProvider);
          //                      _that.viewer.zoomTo(layer)
          return layer
        },
        error: function (msg) {
          console.log(msg);
        }
      });
    }
    /**
     * 跳转模型id
     * @param {*} id
     * @returns
     */
    flyToTiltPhotography(id) {
      const viewer = this.viewer;

      var entitys1 = $G.Query(viewer, { id: "倾斜摄影0" }) ?? {};
      var entitys2 = $G.Query(viewer, { id: "倾斜摄影1" }) ?? {};
      var entitys3 = $G.Query(viewer, { id: "倾斜摄影2" }) ?? {};
      entitys1.show = false;
      entitys2.show = false;
      entitys3.show = false;

      var entitys = $G.Query(viewer, { id: "倾斜摄影" + id });
      if (!entitys) {
        console.warn("没查询到:" + id);
        return;
      }
      entitys.show = true;

      switch (id) {
        case "0":
          $G.Go(viewer, {
            h: 4.61,
            p: -0.5882977335,
            r: 0,
            x: 106.286446,
            y: 38.451525,
            z: 1347.47,
            duration: 3,
          });
          break;
        case "1":
          $G.Go(viewer, {
            h: 5.1,
            p: -0.6077738813,
            r: 0,
            x: 106.273107,
            y: 38.44589,
            z: 720.46,
            duration: 3,
          });
          break;
        case "2":
          $G.Go(viewer, {
            h: 5.4,
            p: -0.5116589552,
            r: 0,
            x: 106.282131,
            y: 38.484625,
            z: 893.46,
            duration: 3,
          });
          break;
        default:
          break;
      }

      // var boundingSphere = entitys.boundingSphere;
      // var cartographic = Cesium.Cartographic.fromCartesian(boundingSphere.center);
      // // var surface = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, options.heightOffset ?? 0);
      // var lng = Cesium.Math.toDegrees(cartographic.longitude);
      // var lat = Cesium.Math.toDegrees(cartographic.latitude);
      // var height = cartographic.height; //模型高度
    }

    /**
     * 加载行政区划
     */
    example_geoJson_load() {
      const viewer = this.viewer;

      // $G.Go(viewer, {
      //   h: 4.73,
      //   p: -0.9620756066,
      //   r: 0,
      //   x: 107.586117,
      //   y: 38.272312,
      //   z: 140467.37,
      //   duration: 3,
      // });

      //#region  行政区块
      const array = {
        name: "银川",
        data: {
          // uri: "http://121.40.42.254:8008/%E9%93%B6%E5%B7%9D-%E8%A1%8C%E6%94%BF%E5%8C%BA%E5%88%92/", //"/assets/geojson/", //
          uri: "./assets/geojson/",
          list: ["贺兰县.geojson", "金凤区.geojson", "灵武市.geojson", "西夏区.geojson", "兴庆区.geojson", "永宁县.geojson", "银川市.geojson"],
        },
      };
      for (let index = 0; index < array.data.list.length; index++) {
        const element = array.data.list[index];
        const uri = array.data.uri;
        let nameTemp = element.split(".")[0];
        if(nameTemp.indexOf("兴庆区") != -1){
          //目前只显示兴庆区的行政区划
          $G.aGeojson(
            viewer,
            {
              name: element.split(".")[0],
              url: `${uri}${element}`,
              polygon: {
                show: true,
                color: "#a9d4eb",
                withAlpha: 0.2,
                outlineColor: "#fff",
                outlineWithAlpha: 0.5,
                outlineWidth: 5,
              },
              polyline: {
                show: true,
                color: "#a9d4eb",
                withAlpha: 0.2,
                width: 2,
                clampToGround: true,
              },
              label: {
                show: true,
                // text: element,
                scale: 0.5,
                fillColor: "#000",
                outlineWidth: 5,
                distanceDisplayCondition: new Cesium.DistanceDisplayCondition(10.0, 10000000.0),
              },
            },
            function (e) {
              console.log(e);
              let entitie = e.entitie;
              switch (entitie.name) {
                case "金凤区":
                  entitie.polygon.material = Cesium.Color.fromCssColorString("#00ff00").withAlpha(0.4);
                  break;
                case "灵武市":
                  entitie.polygon.material = Cesium.Color.fromCssColorString("#b1a14f").withAlpha(0.4);
                  break;
                case "兴庆区":
                  entitie.polygon.material = Cesium.Color.fromCssColorString("#ef8c2b").withAlpha(0.4);
                  break;
                case "西夏区":
                  entitie.polygon.material = Cesium.Color.fromCssColorString("#92478a").withAlpha(0.4);
                  break;
                case "银川市":
                  e.polygon.show = false;
                  break;
                default:
                  break;
              }
            }
          );
        }
        

        /**
         * 删除
         */
        // setTimeout(() => {
        //   for (let index = 0; index < array.data.list.length; index++) {
        //     const element = array.data.list[index];
        //     $G.dMod_X(viewer, { name: element.split(".")[0] });
        //   }
        // }, 3000);
      }

    }

    example_geoJson_load_1(params) {
      const viewer = this.viewer;

      let index_color = 0;
      //#region  行政区块
      const array = {
        name: "银川",
        data: {
          // uri: "http://121.40.42.254:8008/%E9%93%B6%E5%B7%9D-%E8%A1%8C%E6%94%BF%E5%8C%BA%E5%88%92/", //"/assets/geojson/", //
          uri: "./assets/geojson/",
          list: ["业主提供_兴庆区网格数据_Level1.geojson"],
        },
      };
      for (let index = 0; index < array.data.list.length; index++) {
        const element = array.data.list[index];
        const uri = array.data.uri;
        $G.aGeojson(
          viewer,
          {
            name: element.split(".")[0],
            id:params.id,
            url: `${uri}${element}`,
            polygon: {
              show: true,
              color: "#a9d4eb",
              withAlpha: 0.2,
              outlineColor: "#fff",
              outlineWithAlpha: 0.5,
              outlineWidth: 5,
            },
            polyline: {
              show: true,
              color: "#a9d4eb",
              withAlpha: 0.2,
              width: 2,
              clampToGround: true,
            },
            label: {
              show: false,
              // text: element,
              scale: 0.3,
              fillColor: "#000",
              outlineWidth: 5,
              distanceDisplayCondition: new Cesium.DistanceDisplayCondition(10.0, 10000000.0),
            },
          },
          function (e) {
            let entitie = e.entitie;

            entitie.diyType = "geojson";

            var color = '#'+ Math.random().toString(16).substr(-6);  //"#00ff00"   随机生成16进制颜色
            entitie.polygon.material = Cesium.Color.fromCssColorString(color).withAlpha(0.4);
            
          }
        );
        

        /**
         * 删除
         */
        // setTimeout(() => {
        //   for (let index = 0; index < array.data.list.length; index++) {
        //     const element = array.data.list[index];
        //     $G.dMod_X(viewer, { name: element.split(".")[0] });
        //   }
        // }, 3000);
      }

    }

    example_geoJson_load_2(params) {
      const viewer = this.viewer;

      let index_color = 0;
      //#region  行政区块
      const array = {
        name: "银川",
        data: {
          // uri: "http://121.40.42.254:8008/%E9%93%B6%E5%B7%9D-%E8%A1%8C%E6%94%BF%E5%8C%BA%E5%88%92/", //"/assets/geojson/", //
          uri: "./assets/geojson/",
          list: ["业主提供_兴庆区网格数据_Level2.geojson"],
        },
      };
      for (let index = 0; index < array.data.list.length; index++) {
        const element = array.data.list[index];
        const uri = array.data.uri;
        $G.aGeojson(
          viewer,
          {
            name: element.split(".")[0],
            id:params.id,
            url: `${uri}${element}`,
            polygon: {
              show: true,
              color: "#a9d4eb",
              withAlpha: 0.2,
              outlineColor: "#fff",
              outlineWithAlpha: 0.5,
              outlineWidth: 5,
            },
            polyline: {
              show: true,
              color: "#a9d4eb",
              withAlpha: 0.2,
              width: 2,
              clampToGround: true,
            },
            label: {
              show: false,
              // text: element,
              scale: 0.3,
              fillColor: "#000",
              outlineWidth: 5,
              distanceDisplayCondition: new Cesium.DistanceDisplayCondition(10.0, 10000000.0),
            },
          },
          function (e) {
            let entitie = e.entitie;

            entitie.diyType = "geojson";

            var color = '#'+ Math.random().toString(16).substr(-6);  //"#00ff00"   随机生成16进制颜色
            entitie.polygon.material = Cesium.Color.fromCssColorString(color).withAlpha(0.4);
            
          }
        );
        

        /**
         * 删除
         */
        // setTimeout(() => {
        //   for (let index = 0; index < array.data.list.length; index++) {
        //     const element = array.data.list[index];
        //     $G.dMod_X(viewer, { name: element.split(".")[0] });
        //   }
        // }, 3000);
      }

    }
    //销毁网格数据
    destroyGridData(params){

      for(let index = 0; index < this.viewer.dataSources.length; index++){
        if(this.viewer.dataSources.get(index).object.id == params.id){
          this.viewer.dataSources.remove(this.viewer.dataSources.get(index));
        }
      }

    }
    //销毁倾斜摄影
    destroy_TiltPhotography(data){
      var viewer = this.viewer;
      $G.destroy_aMODEL(viewer,{id:data.id});
    }
    //销毁摄像头
    destroy_camera(data){
      var viewer = this.viewer;
      $G.destroy_aMODEL(viewer,{id:data.id});
    }
    //销毁多流摄像头
    destroyMultiStreamCamera(data){
      var viewer = this.viewer;
      $G.destroy_aMODEL(viewer,{id:data.id});
    }

    //多流摄像头
    multiStreamCamera(params){
      var viewer = this.viewer;
      $G.I.mouse.click.multiStreamCamera({params:params,viewer:viewer});
    }


    //加载白膜
    addBaiMo(params){


      let url = "";
      if(window.Intranet){
          //业主服务器
          url = "http://172.31.113.201:6080/数据/周边/银川-白膜/tileset.json";
      }else{
          //阿里云服务器
          url = "http://121.40.42.254:8008/%E9%93%B6%E5%B7%9D-%E7%99%BD%E8%86%9C/tileset.json";
      }

      var tileset = this.viewer.scene.primitives.add(new Cesium.Cesium3DTileset({
          url: url, //数据路径
          maximumScreenSpaceError: 2, //最大的屏幕空间误差
          maximumNumberOfLoadedTiles: 1000, //最大加载瓦片个数
      }));

      tileset.name = "jzw";
      tileset.diyId = params.id;

      // this.viewer.flyTo(tileset,{
      //     duration:3, // 时间
      //     // offset:new Cesium.HeadingPitchRange(1.682848565519711, -0.23204901325136928, 120) // 偏移
      //  });

       tileset.readyPromise.then(function (tileset) {
        tileset.style = new Cesium.Cesium3DTileStyle({
          // color: {
          // conditions: [
          //   ["true", "color('rgb(12, 134, 172)',1)"]
          // ]
          // }
        });

        tileset.customShader = customShader;
      })
    }

    //白膜特效
    baiMoEffects(){

      $G.baiMoEffects(this.viewer,{});
    }

    //销毁白膜
    destroyBaiMo(params){

      for(let i = 0;i < this.viewer.scene.primitives._primitives.length;i++){

        if(this.viewer.scene.primitives._primitives[i].diyId == params.id){
          this.viewer.scene.primitives._primitives[i].destroy();
          break;
        }
      }

    }

    //添加摄像头
    add_camera(data) {   

      var viewer = this.viewer;

      var model = $G.aMODEL(viewer, {
        type: 'camera',
        id: data.id,
        url: "/static/3d/assets/model/" + data.type + ".glb",
        scale: 1.0,
        position: data.position,
      });
      model.tag = "摄像头";

      

      // var arr = [
      //   { id: "3FD815955E4811ECA56200163E0132C0", camera: "", name: "摄像头1", position: { h: 0, p: 0, r: 0, x: 106.265058, y: 38.449457, z: 14 }, type: "摄像头-枪机" },
      //   { id: "3FDA05DE5E4811ECA56200163E0132C0", camera: "", name: "摄像头2", position: { h: 0, p: 0, r: 0, x: 106.265681, y: 38.4493, z: 9 }, type: "摄像头-球机" },
      //   { id: "3FDBCFFA5E4811ECA56200163E0132C0", camera: "", name: "摄像头3", position: { h: 0, p: 0, r: 0, x: 106.265476, y: 38.450477, z: 15 }, type: "摄像头-球机" },
      //   { id: "3FDD9A165E4811ECA56200163E0132C0", camera: "", name: "摄像头4", position: { h: 0, p: 0, r: 0, x: 106.26614, y: 38.450305, z: 14 }, type: "摄像头-枪机" },
      //   { id: "3FDF3E055E4811ECA56200163E0132C0", camera: "", name: "摄像头5", position: { h: 0, p: 0, r: 0, x: 106.266313, y: 38.449566, z: 14 }, type: "摄像头-枪机" },
      //   { id: "3FE12E4E5E4811ECA56200163E0132C0", camera: "", name: "摄像头6", position: { h: 0, p: 0, r: 0, x: 106.266247, y: 38.448954, z: 17 }, type: "摄像头-球机" },
      // ];

      // let uri = "/static/3d/assets/model/";
      // for (let index = 0; index < arr.length; index++) {
      //   const element = arr[index];
      //   var model = $G.aMODEL(viewer, {
      //     id: element.id,
      //     url: uri + element.type + ".glb",
      //     scale: 1.0,
      //     position: element.position,
      //   });
      //   model.name = "摄像头";
      // }
      // // console.log(window)
      // $G.I.mouse.click.entityColor({
      //   viewer:viewer,
      //   constraint: { name: "摄像头" },
      //   style: { color: "#4395ff", shapeTransparency: 80 },
      // });
    }
    /**
     * 加载资源
     * @param {*} element
     * @param {*} callback
     */
    writeln = (element, callback) => {
      let head = document.getElementsByTagName("head")[0],
        _ = $(element)[0];
      _.onload = _.onreadystatechange = function () {
        if (!this.readyState || this.readyState === "loaded" || this.readyState === "compe") {
          callback && callback();
          // Handle memory leak in IE
          _.onload = _.onreadystatechange = null;
          if (head && _.parentNode) {
            head.removeChild(_);
          }
        }
      };
      // Use insertBefore instead of appendChild  to circumvent an IE6 bug.
      head.insertBefore(_, head.firstChild);
    };
    //#endregion
  }

  window.Gear = gear;
})(window);
